
package com.compuvest.web;

// <editor-fold defaultstate="collapsed" desc="import">
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import java.util.logging.Level;
import java.util.logging.Logger;
// </editor-fold>

public final class SessionEvent implements HttpSessionListener {

    private final static Logger log = Logger.getLogger(SessionEvent.class.getName());

    private Basket basket;
    private HttpSession session;

// <editor-fold defaultstate="collapsed" desc="sessionCreated()">
    @Override
    public synchronized void sessionCreated(HttpSessionEvent event) {

        session = event.getSession();
        try {
            basket = new Basket();
            session.setAttribute("basket", basket);
        }
        catch(Exception ex) {
            log.log(Level.SEVERE, "sessionCreated()", ex);
        }
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="sessionDestroyed()">
    @Override
    public synchronized void sessionDestroyed(HttpSessionEvent event) {

        session = event.getSession();
        try {

            SQLBean sb = (SQLBean)session.getServletContext().getAttribute("sb");
            if(sb == null) {
                log.log(Level.SEVERE, "sb=null");
                return;
            }

            //Basket basket = (Basket)session.getAttribute("basket");
            // save basket
            if(basket.notEmpty()) {
                sb.setBasket(basket, session.getId());
            }

            Customer cust = basket.getCustomer();
            if(cust != null && cust.getCustomerID() == 0) {

                Mail mail = (Mail)session.getServletContext().getAttribute("mail");
                if(mail == null) {
                    log.log(Level.SEVERE, "mail=null");
                    return;
                }

//              mail.sendLostCustomerDetailToMe(basket, makeCust);


                // send email to lost customer
                mail.sendEmailToLostCustomerDetail(basket);

                // create new customer
                sb.updateCustomer(cust, basket.getCompuvestCookies().getIPAddress());

            }

            // delete
            session.removeAttribute("basket");
            basket = null;
            session = null;
        }
        catch(Exception ex) {
            log.log(Level.SEVERE, "sessionDestroyed()", ex);
        }

    }
// </editor-fold>
}
